package com.example.huainanlive.server

import android.util.Log
import com.demon.net.NetConstant
import com.example.huainanlive.MyApplication
import okhttp3.FormBody
import okhttp3.FormBody.Builder
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.MultipartBody
import okhttp3.Request
import okhttp3.Response
import java.net.URLDecoder
import java.nio.charset.Charset

/**
 * 类简要描述
 * <p/>
 * <p>
 * 类详细描述
 * </p>
 *
 * @author zhaozeyang
 * @date 2020/8/25
 */
class LoginParamInterceptor : Interceptor {
  override fun intercept(chain: Chain): Response {
    val request = chain.request()
    val newRequest =
      when (request.method) {
        NetConstant.METHOD_GET -> {
          appendGet(request)
        }
        NetConstant.METHOD_POST -> {
          appendPost(request)
        }
        else -> {
          request
        }
      }
    return chain.proceed(newRequest)
  }

  private fun appendGet(request: Request): Request {
    val paramsMap = mutableMapOf<String, String>()
    val paramKeys = request.url.queryParameterNames
    for (key in paramKeys) {
      paramsMap[key] = request.url.queryParameter(key) ?: ""
    }
    return request.newBuilder().url(
        request.url.newBuilder()
            .addQueryParameter(REQUEST_DEVICE_VERSION, MyApplication.AppInfo.versionName)
            .addQueryParameter(REQUEST_LOGIN_TYPE, REQUEST_LOGIN_TYPE_ANDROID_VALUE)
            .addQueryParameter(REQUEST_REGISTRATION_ID, "")
            .build()
    ).build()
  }

  private fun appendPost(request: Request): Request {
    val requestBody = request.body ?: return request
    when (requestBody) {
      is FormBody -> {
        return appendParamToFormBody(requestBody, request)
      }
      is MultipartBody -> {
        return appendParamToMultiPartBody(requestBody, request)
      }
      else -> {
        Log.d("CommonParamInterceptor", " type is " + requestBody.javaClass.name)
      }
    }
    return request
  }

  private fun appendParamToMultiPartBody(
    requestBody: MultipartBody,
    request: Request
  ): Request {
    return request
  }

  private fun appendParamToFormBody(
    requestBody: FormBody,
    request: Request
  ): Request {
    val bodyBuilder = Builder(Charset.defaultCharset())
    var formBody: FormBody = requestBody
    // 先复制原来的参数
    val paramsMap = mutableMapOf<String, String>()
    for (i in 0 until formBody.size) {
      bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i))
      // 生成签名的时候要解码，这里从request里面取出的参数是经过utf-8转码后的字符串，但是生成签名要用原始字符串进行生成
      paramsMap[formBody.encodedName(i)] = URLDecoder.decode(formBody.encodedValue(i), Charsets.UTF_8.name())
    }
    // 添加公共参数

    formBody = bodyBuilder
        .addEncoded(REQUEST_LOGIN_TYPE, REQUEST_LOGIN_TYPE_ANDROID_VALUE)
        .addEncoded(REQUEST_DEVICE_VERSION, MyApplication.AppInfo.versionName)
        .addEncoded(REQUEST_REGISTRATION_ID, "123")
        .build()
    return request.newBuilder().post(formBody).build()
  }

  companion object {
    const val REQUEST_DEVICE_VERSION = "app_version"
    const val REQUEST_LOGIN_TYPE = "last_login_type"
    const val REQUEST_REGISTRATION_ID = "registration_id"
    const val REQUEST_LOGIN_TYPE_ANDROID_VALUE = "android"
  }
}